package cn.com.libertymutual.sp.action;

import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.ResourceAccessException;

import com.google.common.collect.Maps;

import cn.com.libertymutual.core.annotation.SystemValidate;
import cn.com.libertymutual.core.base.dto.PrpLmAgent;
import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.util.Current;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.bean.TbSpStoreProduct;
import cn.com.libertymutual.sp.dto.PrpSalesPerson;
import cn.com.libertymutual.sp.dto.TQuerySalesResponseDto;
import cn.com.libertymutual.sp.service.api.BranchSetService;
import cn.com.libertymutual.sp.service.api.CaptchaService;
import cn.com.libertymutual.sp.service.api.ShopService;
import cn.com.libertymutual.sp.service.api.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/nol/shop")
public class ShopController {
	private Logger log = LoggerFactory.getLogger(getClass());
	@Resource
	private CaptchaService captchaService;// 图形验证码
	@Resource
	private ShopService shopService;
	@Resource
	private UserService userService;
	@Resource
	private BranchSetService branchSetService;// 机构
	@Resource
	private RedisUtils redis;

	@RequestMapping(value = "/findShopInfo")
	public ServiceResult findShopInfo(String userCode, String type, HttpServletRequest request) {
		// 查找其他店主信息 请不要使用Current.userCode.get()

		return shopService.findShopInfo(userCode, request, type);
	}

	@RequestMapping(value = "/setStateType")
	@SystemValidate(validate = false, description = "无需校验接口")
	public ServiceResult setStateType(String userCode, String stateType) {
		return shopService.setStateType(Current.userCode.get(), stateType);
	}

	// @RequestMapping(value = "/getStateType")
	// public ServiceResult getStateType(String userCode) {
	// return shopService.productManage(Current.userCode.get(),
	// branchCode,riskCode);
	// }

	@RequestMapping(value = "/productManage")
	public ServiceResult productManage(String userCode, String branchCode, String riskCode) {
		return shopService.productManage(Current.userCode.get(), branchCode, riskCode);
	}

	@RequestMapping(value = "/saveStorePro")
	@SystemValidate(validate = false, description = "无需校验接口")
	public ServiceResult saveStorePro(@RequestBody List<TbSpStoreProduct> storeList) {
		return shopService.saveStoreProductList(storeList);
	}

	@RequestMapping(value = "/productList")
	public ServiceResult shopProductFind(String userCode, String type, int pageNumber, int pageSize) {
		// 查找其他店主信息 请不要使用Current.userCode.get()
		return shopService.shopProductFind(userCode, type, pageNumber, pageSize);
	}

	@ApiOperation(value = "申请业务关系代码", notes = "测试")
	@PostMapping(value = "/applyAgreementNo")
	@ApiImplicitParams(value = { @ApiImplicitParam(name = "userCode", value = "用户编码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "applyType", value = "申请类型", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "areaId", value = "地区ID", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "areaCode", value = "地区编码", required = true, paramType = "query", dataType = "String"), })
	public ServiceResult updateAgreementNoByApply(HttpServletRequest request, String userCode, String applyType, Integer areaId, String areaCode) {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			sr = shopService.updateAgreementNoByApply(request, sr, Current.userCode.get(), applyType, areaId, areaCode);
		} catch (IOException | ParseException | MessagingException e) {
			log.info("申请业务关系代码异常：{}", e.toString());
		}
		return sr;
	}

	@ApiOperation(value = "查询是否有专属佣金配置", notes = "测试")
	@ApiImplicitParams(value = { @ApiImplicitParam(name = "userCode", value = "用户编码", required = true, paramType = "query", dataType = "String") })
	@RequestMapping(value = "/findEYongjCountByUserCode")
	public ServiceResult findEYongjCountByUserCode(HttpServletRequest request, HttpServletResponse response) {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			sr = shopService.findEYongjCountByUserCode(sr, Current.userCode.get());
		} catch (Exception e) {
			sr.setResult("查询是否有专属佣金配置异常");
			log.warn("查询是否有专属佣金配置异常:{}", e.toString());
			log.error("{}", e);
		}
		return sr;
	}

	@ApiOperation(value = "查询业务关系代码& 图形码", notes = "测试")
	@ApiImplicitParams(value = { @ApiImplicitParam(name = "identCode", value = "请求标识码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "imgCode", value = "图形码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "agreementNo", value = "关系代码", required = true, paramType = "query", dataType = "String") })
	@RequestMapping(value = "/findByAgreementNo_img")
	public ServiceResult findAgreementNo(HttpServletRequest request, HttpServletResponse response, String identCode, String imgCode,
			String agreementNo) {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			// 校验-图形码
			if (!captchaService.validationCaptcha(request, sr, redis, imgCode)) {
				return sr;
			}
			// Current.userCode.get(),
			sr = shopService.findByAgreementNo(request, sr, agreementNo);
		} catch (IOException e) {
			sr.setResult("查询业务关系代码超时");
			log.warn("查询业务关系代码IO异常:" + e.toString());
		} catch (ResourceAccessException e) {
			sr.setResult("资源访问异常");
			log.warn("查询业务关系代码资源访问异常:" + e.toString());
		} catch (ParseException e) {
			sr.setResult("数据解析异常");
			log.warn("查询业务关系代码数据解析异常:" + e.toString());
		} catch (Exception e) {
			sr.setResult("查询业务关系代码异常");
			log.warn("查询业务关系代码异常:" + e.toString());
		}
		return sr;
	}

	@ApiOperation(value = "查询业务关系代码-店铺", notes = "测试")
	@ApiImplicitParams(value = { @ApiImplicitParam(name = "userCode", value = "用户编码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "agreementNo", value = "业务关系代码", required = true, paramType = "query", dataType = "String") })
	@RequestMapping(value = "/findAgreementNoOfShop")
	public ServiceResult findAgreementNo(HttpServletRequest request, HttpServletResponse response, String agreementNo) {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			sr = shopService.findByAgreementNo(request, sr, agreementNo);
		} catch (IOException e) {
			sr.setResult("查询业务关系代码超时");
			log.warn("查询业务关系代码IO异常:" + e.toString());
		} catch (ResourceAccessException e) {
			sr.setResult("资源访问异常");
			log.warn("查询业务关系代码资源访问异常:" + e.toString());
		} catch (ParseException e) {
			sr.setResult("数据解析异常");
			log.warn("查询业务关系代码数据解析异常:" + e.toString());
		} catch (Exception e) {
			sr.setResult("查询业务关系代码异常");
			log.warn("查询业务关系代码异常:" + e.toString());
		}
		return sr;
	}

	@ApiOperation(value = "查询销售人员信息", notes = "测试")
	@ApiImplicitParams(value = { @ApiImplicitParam(name = "identCode", value = "请求标识码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "agreementNo", value = "关系代码", required = true, paramType = "query", dataType = "String") })
	@RequestMapping(value = "/findSealesPersos")
	public ServiceResult findSealesPersos(HttpServletRequest request, HttpServletResponse response, String identCode, String agreementNo) {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			// 校验输入的关系代码信息是否被篡改
			Object obj = redis.get(Constants.AGREEMEN_TINFO + request.getSession().getId());
			if (null == obj) {
				sr.setResult("请重新输入业务关系代码");
			}
			PrpLmAgent prpLmAgent = (PrpLmAgent) obj;
			///String redisAgrNo = prpLmAgent.getAgreementNo();// 关系代码
			// 校验
			if (prpLmAgent == null || !prpLmAgent.getAgreementNo().equals(agreementNo)) {
				sr.setResult("请输入正确的业务关系代码");
				return sr;
			}

			// // 测试数据
			// TQuerySalesResponseDto dto = new TQuerySalesResponseDto();
			// dto.setStatus(true);
			// dto.setFlowId("LBN0011513058907464");
			// dto.setResultCode("0");
			// dto.setUuId("360000000060362fb00160495850ff051d");
			// PrpSalesPerson salesPerson = new PrpSalesPerson();
			// salesPerson.setAgreementNo("SHC000006");
			// salesPerson.setSaleVocationCardNo("testMoto");
			// salesPerson.setSaleName("四川个人");
			// List<PrpSalesPerson> sealesPersos = new ArrayList<>();
			// sealesPersos.add(salesPerson);
			// dto.setSealesPersos(sealesPersos);
			// sr.setResult(dto);
			// sr.setSuccess();

			sr = branchSetService.getSaleName(agreementNo);
			// 如果存在销售人员信息，则对每一个销售人员名称和销售编码进行保存，便于后期校验篡改信息
			if (sr.getState() == ServiceResult.STATE_SUCCESS) {
				TQuerySalesResponseDto dto = (TQuerySalesResponseDto) sr.getResult();
				List<PrpSalesPerson> persons = dto.getSealesPersos();
				HashMap<String, String> map = Maps.newHashMap();
				for (PrpSalesPerson person : persons) {
					if (StringUtils.isNotBlank(person.getSaleName()) && StringUtils.isNotBlank(person.getSaleVocationCardNo())) {
						map.put(person.getSaleVocationCardNo(), person.getSaleName());
					}
				}
				// 零时存储销售人员信息，用于校验
				redis.setWithExpireTime(Constants.SALE_PERSON_TINFO + request.getSession().getId(), map, Constants.SINGLE_REQUEST_TIMEOUT_SECONDS);
			}

		} catch (Exception e) {
			log.warn("查询机构代码异常:" + e.toString());
		}
		return sr;
	}

	@ApiOperation(value = "查询所有常驻地区", notes = "测试")
	@RequestMapping(value = "/findAllHotArea")
	public ServiceResult findAllHotArea() {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			return shopService.findAllHotArea();
		} catch (Exception e) {
			log.warn("查询所有地区异常:" + e.toString());
		}
		return sr;
	}

	@ApiOperation(value = "常驻地区--开店/店铺设置", notes = "测试")
	@PostMapping(value = "/openStoreByArea")
	@ApiImplicitParams(value = { @ApiImplicitParam(name = "userCode", value = "用户编码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "agreementNo", value = "业务关系代码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "areaCode", value = "地区编码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "saleCode", value = "销售编码", required = false, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "saleName", value = "销售人员", required = false, paramType = "query", dataType = "String"), })
	public ServiceResult updateStoreStateByArea(HttpServletRequest request, String userCode, String agreementNo, String areaCode, String saleCode,
			String saleName) {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			sr = shopService.updateStoreStateByArea(request, sr, Current.userCode.get(), agreementNo, areaCode, saleCode, saleName);
		} catch (Exception e) {
			log.info("常驻地区--开店/店铺设置 异常：", e.toString());
			e.printStackTrace();
		}
		return sr;

	}

	@ApiOperation(value = "有业务关系代码人员--开店", notes = "测试")
	@PostMapping(value = "/openStoreByAgreement")
	@ApiImplicitParams(value = { @ApiImplicitParam(name = "userCode", value = "用户编码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "agreementNo", value = "业务关系代码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "saleCode", value = "销售编码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "saleName", value = "销售人员", required = true, paramType = "query", dataType = "String"), })
	public ServiceResult updateStoreStateByAgreement(HttpServletRequest request, String userCode, String agreementNo, String saleCode,
			String saleName) {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			sr = shopService.updateStoreStateByAgreement(request, sr, Current.userCode.get(), agreementNo, saleCode, saleName);
		} catch (Exception e) {
			log.info("有业务关系代码人员--开店/店铺设置 异常：", e.toString());
			e.printStackTrace();
		}
		return sr;

	}

	/*
	 * 店铺佣金比例
	 */
	@ApiOperation(value = "店铺佣金比例", notes = "店铺佣金比例")
	@PostMapping(value = "/shopRate")
	@ApiImplicitParams(value = { @ApiImplicitParam(name = "userCode", value = "用户编码", required = true, paramType = "query", dataType = "String"), })
	@SystemValidate(validate = false, description = "无需校验接口")
	public ServiceResult shopRate(String userCode, String branchCode) {
		return shopService.shopRate(Current.userCode.get(), branchCode);
	}

	@PostMapping(value = "/mergeAccount")
	public ServiceResult mergeAccount(String userCode) {
		ServiceResult sr = new ServiceResult();
		sr.setResult(shopService.mergeAccount(Current.userCode.get()));
		return sr;
	}

}
